import axios from "axios";
import { message } from "ant-design-vue";
import { useMemberStore } from "../store";
import type {
  AxiosResponse,
  AxiosInstance,
  ResponseType,
  RawAxiosRequestHeaders,
  AxiosHeaders,
  Method,
} from "axios";
import { useCookie } from "nuxt/app";

axios.defaults.withCredentials = true;
const instance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL,
  timeout: 60000,
  withCredentials: true,
});
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const memberStore = useMemberStore();
    if (memberStore.profile) {
      config.headers.Authorization = "Bearer " + memberStore.profile.token;
    }

    config.headers['Lang'] = useCookie('lang').value || 'en'

    // 配置cookie
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    return response;
  },
  function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

interface DataResult<T> {
  code: number;
  msg: string;
  data: T;
  message?: string;
  img?: string;
  captcha?: string;
  key?: string;
  ret?: boolean;
}

type MethodsHeaders = Partial<
  {
    [Key in Method as Lowercase<Key>]: AxiosHeaders;
  } & { common: AxiosHeaders }
>;

interface RequestParams {
  url: string;
  method: "GET" | "POST" | "PUT" | "DELETE";
  data?: Object;
  responseType?: ResponseType;
  headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
}

export default <T>(params: RequestParams) => {
  return new Promise<DataResult<T>>((resolve, reject) => {
    instance({
      ...params,
    })
      .then((res: AxiosResponse<DataResult<T>>) => {
        // 请求失败
        if (res.data.code === 0) {
          resolve(res);
          return;
        }
        if (res.data.code == 10501) {
          res.msg = "server error";
          resolve(res);
          return;
        }
        // 请求成功
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

// 封装 useFetch
